// 引入VueRouter
import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user.store'
import { showSuccessToast, showFailToast } from 'vant'
// 创建路由表
const routes = [
  {
    path: '/',
    redirect: '/Home',
    component: () => import('../views/Home/Home.vue')
  },
  {
    path: '/Home',
    meta: {
      showTab: true
    },
    name: 'Home',
    component: () => import('../views/Home/Home.vue')
  },
  {
    path: '/Classify',
    meta: {
      showTab: true
    },
    name: 'Classify',
    component: () => import('../views/Classify/Classify.vue')
  },
  {
    path: '/Cart',
    meta: {
      showTab: true,
      auth: true
    },
    name: 'Cart',
    component: () => import('../views/Cart/Cart.vue')
  },
  {
    path: '/Mine',
    meta: {
      showTab: true,
      auth: true
    },
    name: 'Mine',
    component: () => import('../views/Mine/Mine.vue')
  },
  {
    path: '/Login',
    component: () => import('../views/Login/Login.vue')
  },
  {
    path: '/Register',
    component: () => import('../views/Register/index.vue')
  },
  {
    path: '/List',
    name: 'List',
    component: () => import('../views/List/List.vue')
  },
  {
    path: '/AddressList',
    meta: {
      auth: true
    },
    component: () => import('../views/Address/AddressList.vue')
  },
  {
    path: '/AddressEdit',
    name: 'AddressEdit',
    component: () => import('../views/Address/AddressEdit.vue')
  },
  // 商品详情页面
  {
    path: '/GoodsDetail',
    name: 'GoodsDetail',
    // meta: {
    //   auth: true
    // },
    component: () => import('../views/GoodsDetail/Index.vue')
  },
  // 订单确认页面
  {
    path: '/OrderConfirm',
    name: 'OrderConfirm',
    meta: {
      auth: true
    },
    component: () => import('../views/Order/OrderConfirm.vue')
  },
  // 订单列表页
  {
    path: '/OrderList',
    name: 'OrderList',
    meta: {
      auth: true
    },
    component: () => import('../views/Order/OrderList.vue')
  },
  // 搜索列表页
  {
    path: '/SearchList',
    name: 'SearchList',
    component: () => import('../views/List/SearchList.vue')
  }
]
// 创建路由并挂载路由表
const router = createRouter({
  routes,
  history: createWebHistory()
})
// 路由导航守卫
router.beforeEach(async (to, from, next) => {
  if (to.meta.auth) {
    if (localStorage.getItem('token')) {
      const res = await useUserStore().getUserInfo()
      if (res.code === '10100') {
        next()
      } else {
        localStorage.removeItem('token')
        showFailToast('用户登录已过期请重新登陆')
        next('/Login')
      }
    } else {
      console.log('请先登录')
      next('/Login')
    }
  } else {
    next()
  }
})

export default router
